<template>
	<view class="overall">
		<view class="title">
			<view class="name" @click="handleClickLeft">
				<wd-icon name="thin-arrow-left" size="18px"></wd-icon>
				<view>{{name.name}}</view>
			</view>
		</view>
		<view class="content">
			<!-- 日历 -->
			<view class="calendar" @touchstart="handleTouchStart" @touchend="handleTouchEnd">
				<view class="header">
					<!-- <view>{{ year }} 年 {{ month + 1 }} 月</view> -->
				</view>
				<view class="days-of-week">
					<view v-for="day in daysOfWeek" :key="day">{{ day }}</view>
				</view>
				<view class="dates">
					<view v-for="(date, index) in dates" :key="index"
						:class="{ 'not-current-month': date.month !== month, 'today': date.isToday }"
						:style="date.day==myday?'background-color:#A6A6A6;':''" @click="checked(date.day)">
						<view>{{ date.day }}</view>
					</view>
				</view>
			</view>
			<wd-status-tip image-size="60" v-if="doctor==null?true:false" image="content" tip="暂无内容" />

			<view class="tiem" v-if="doctor==null?false:true" v-for="(item, index) in office" :key="index">
				<view class="doctor">
					
					<view>
						<view>
							<view>{{item.doctor.name}}</view>
							<view>{{item.doctor.duties}}</view>
						</view>
						<view>
							{{item.doctor.good}}
						</view>
					</view>
				</view>
				<wd-status-tip image-size="60" v-if="item.office==null?true:false" image="content" tip="暂无内容" />
				<view class="list" v-if="item.office==null?false:true">
					<view
						v-for="(items, index) in item.office==null?item.office:item.office.sort((a, b) => a.time - b.time)"
						:key="index" :class=" items.num>=items.source?'notLeft':'leftover'">
						<view>
							<view>{{items.date}}</view>
							<view>
								{{
								new Date(items.date).getDay()==0?'（周日）'
								:new Date(items.date).getDay()==1?'（周一）'
								:new Date(items.date).getDay()==2?'（周二）'
								:new Date(items.date).getDay()==3?'（周三）'
								:new Date(items.date).getDay()==4?'（周四）'
								:new Date(items.date).getDay()==5?'（周五）'
								:new Date(items.date).getDay()==6?'（周六）':''
								 }}
							</view>
							<view v-if="items.time==1?true:false">上午</view>
							<view v-if="items.time==2?true:false">下午</view>
						</view>

						<view v-if="items.num>=items.source?false:true">
							<view>￥{{doctor[0].money}}</view>
							<view @click="identify(item,items)">剩余{{ items.source - items.num}}</view>
						</view>

						<view v-if="items.num>=items.source?true:false">
							<view>约满</view>
						</view>
					</view>
				</view>
			</view>


		</view>
	</view>
</template>

<script lang="ts" setup>
	import { computed, ref } from 'vue';
	import { work, details } from '@/api/index.js';

	const contentList = ref([]);
	const doctor = ref([]);
	const office = ref([]);
	const name = ref([]);

	function handleClickLeft() {
		uni.navigateBack();
	}
	// 日历
	const year = ref(new Date().getFullYear());
	const month = ref(new Date().getMonth());
	const daysOfWeek = ['日', '一', '二', '三', '四', '五', '六',];
	const day = ref(new Date().getDate());
	const myday = ref(null);

	const dates = computed(() => {
		const today = new Date().getDate(); // 获取今天的日期
		const firstDayOfMonth = new Date(year.value, month.value, 1).getDay();
		const totalDaysInMonth = new Date(year.value, month.value + 1, 0).getDate();
		const datesArray = [];
		for (let i = 1; i <= totalDaysInMonth; i++) {
			const isToday = i === today && month.value === new Date().getMonth(); // 判断是否为今天
			datesArray.push({ day: i, month: month.value, isToday: isToday });
		}
		return [
			...Array(firstDayOfMonth).fill({ day: '', month: '' }),
			...datesArray,
		];
	});



	function event() {
		uni.getStorage({
			key: 'doctor',
			success: function (res) {
				console.log(res.data); // 输出存储的数据对象
				name.value = res.data;
				details({ depart_id: res.data.id }).then(res => {
					console.log(res.data);
					doctor.value = res.data;
					const newmonth = (month.value + 1).toString().padStart(2, '0'); // 月份从 0 开始，需要加 1，并补齐两位
					const newday = day.value.toString().padStart(2, '0'); // 补齐两位
					const formattedDate = `${year.value}-${newmonth}-${newday}`;
					console.log(formattedDate);
					if (res.data != null) {
						(async () => {
							const mergedArray = await Promise.all(
								res.data.map(async (item) => {
									const officeData = await work({
										depart_id: item.depart_id,
										date: formattedDate,
									});
									// 确保 officeData 是数组类型
									if (Array.isArray(officeData)) {
										officeData.sort((a, b) => a.time - b.time);
									}
									return {
										doctor: item,
										office: officeData.data,
									};
								})
							);
							office.value = mergedArray;
							console.log(mergedArray); // 输出合并后的数组
						})();
					}


				})
			}
		});

	}
	event();

	function checked(days) {
		myday.value = days;
		uni.getStorage({
			key: 'doctor',
			success: function (res) {
				details({ depart_id: res.data.id }).then(res => {
					console.log(res.data);
					doctor.value = res.data;
					const newmonth = (month.value + 1).toString().padStart(2, '0'); // 月份从 0 开始，需要加 1，并补齐两位
					const newday = days.toString().padStart(2, '0'); // 补齐两位
					const formattedDate = `${year.value}-${newmonth}-${newday}`;
					console.log(formattedDate);
					if (res.data != null) {
						(async () => {
							const mergedArray = await Promise.all(
								res.data.map(async (item) => {
									const officeData = await work({
										depart_id: item.depart_id,
										date: formattedDate,
									});
									// 确保 officeData 是数组类型
									if (Array.isArray(officeData)) {
										officeData.sort((a, b) => a.time - b.time);
									}
									if (day.value > days && newmonth > month.value.toString()) {
										return {
											doctor: item,
											office: null,
										};
									} else {
										return {
											doctor: item,
											office: officeData.data.reverse(),
										};
									}
								})
							);
							office.value = mergedArray;
							console.log(mergedArray); // 输出合并后的数组
						})();
					}
				})
			}
		});
	}

	function previousMonth() {
		if (month.value === 0) {
			year.value--;
			month.value = 11;
		} else {
			month.value--;
		}
	}
	function nextMonth() {
		if (month.value === 11) {
			year.value++;
			month.value = 0;
		} else {
			month.value++;
		}
	}

	const startY = ref(0);
	const handleTouchStart = (event) => {
		startY.value = event.touches[0].clientY;
	};

	const handleTouchEnd = (event) => {
		const endY = event.changedTouches[0].clientY;
		if (endY - startY.value > 50) {
			console.log('下划操作');
			myday.value = null;
			previousMonth();
		} else if (startY.value - endY > 50) {
			console.log('上划操作');
			myday.value = null;
			nextMonth();
		}
	};

	function identify(item, items) {
		console.log(item);
		// 医生信息
		uni.setStorage({
			key: 'details',
			data: item.doctor,
			success: function () {
				console.log('数据存储成功');
			}
		});

		console.log(items);
		uni.setStorage({
			key: 'time',
			data: items,
			success: function () {
				console.log('数据存储成功');
			}
		});

		uni.navigateTo({
			url: '/pages/registered/registered',
		})
	}
</script>

<style scoped>
	.overall {
		width: 100%;
		padding-bottom: 30vh;
	}

	.title {
		width: 100%;
		height: 180rpx;
		background-color: #00DACA;
		color: white;
		display: flex;
		align-items: center;
		position: fixed;
		top: 0;
	}

	.name {
		display: flex;
		align-items: center;
		font-weight: bold;
		font-size: 42rpx;
		margin-top: 50rpx;
		margin-left: 3%;
	}

	.name>view {
		margin-left: 30rpx;
	}

	.content {
		width: 94%;
		margin: 180rpx 3%;
	}

	.calendar {
		min-height: 35vh;
		border-bottom: #EBEBEB 6rpx solid;
	}

	.days-of-week {
		width: 100%;
		display: flex;
		border-bottom: #EBEBEB 5rpx solid;
	}

	.days-of-week>view {
		width: 92rpx;
		height: 60rpx;
		margin: 5rpx 7rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.dates {
		width: 100%;
		display: flex;
		flex-wrap: wrap;
	}

	.dates>view {
		width: 12.5%;
		height: 70rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 4rpx 7rpx;
	}

	.today {
		color: #00DACA;
	}

	.tiem {
		width: 100%;
	}

	.doctor image {
		width: 50rpx;
		height: 60rpx;
	}

	.doctor {
		width: 100%;
		height: 140rpx;
		display: flex;
		justify-content: center;
		padding-top: 30rpx;
	}

	.doctor>view:first-child {
		width: 100rpx;
		height: 100rpx;
		background-color: #E5E5E5;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 10000rpx;
	}

	.doctor>view:last-child>view:first-child {
		display: flex;
		margin-bottom: 15rpx;
	}

	.doctor>view:last-child {
		width: 72%;
		margin-left: 5%;
		font-size: 28rpx;
	}

	.doctor>view:last-child>view:first-child>view:first-child {
		font-weight: bold;
		padding-right: 40rpx;
	}

	.doctor>view:last-child>view:first-child>view:last-child {
		border-left: 5rpx #EEEEEE solid;
		padding-left: 20rpx;
		color: #A6A6A6;
	}

	.doctor>view:last-child>view:last-child {
		width: 90%;
		font-size: 28rpx;
		color: #A6A6A6;
		word-wrap: break-word;
	}

	.list {
		width: 100%;
		margin-top: 10rpx;
		font-size: 28rpx;
	}

	.list>view {
		border-bottom: #EBEBEB 6rpx solid;
		display: flex;
		height: 130rpx;
		justify-content: space-between;
	}

	.list>view>view {
		display: flex;
		min-width: 35%;
		justify-content: space-between;
		align-items: center;
	}

	.notLeft {
		color: #A6A6A6;
	}

	.leftover>view:first-child {
		color: #00DACA;
	}

	.leftover>view:last-child>view:first-child {
		color: #EC5C28;
		margin-right: 30rpx;
	}

	.leftover>view:last-child>view:last-child {
		background-color: #2EC7C9;
		color: white;
		width: 100rpx;
		padding: 10rpx 5rpx;
		border-radius: 10rpx;
		white-space: nowrap;
		text-align: center;
	}
</style>